package com.lottery.im.module.main.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.base.BaseFragmentActivity;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.login.ui.LoginFragment;
import com.lottery.im.module.main.presenter.MainPresenter;
import com.lottery.im.module.main.view.MainView;
import com.lottery.im.module.tim.business.LoginBusiness;
import com.lottery.im.module.tim.event.FriendshipEvent;
import com.lottery.im.module.tim.event.GroupEvent;
import com.lottery.im.module.tim.event.MessageEvent;
import com.lottery.im.module.tim.event.RefreshEvent;
import com.lottery.im.module.tim.utils.PushUtil;
import com.lottery.im.util.AppManagerUtil;
import com.lottery.im.util.SPUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.lottery.im.widget.floatwindow.FloatWindow;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.sns.TIMAddFriendRequest;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.tencent.imsdk.ext.sns.TIMFriendshipManagerExt;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lianwufeng on 2018/5/28.
 */

public class MainActivity extends BaseFragmentActivity<MainPresenter> implements MainView,
    TIMCallBack {

  private boolean isTheOneBack = true;

  @Override protected int getContextViewId() {
    return R.id.activity_home;
  }

  @Override protected void initPresenter() {
    presenter = new MainPresenter(this, this, this);
    presenter.init();
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RxBus.get().register(this);
    setTIMUserConfig();
    if (savedInstanceState == null) {
      String token = (String) SPUtils.get(this, SpKeyConstant.TOKEN_KEY, "");
      String userInfo = (String) SPUtils.get(this, SpKeyConstant.USERINFO_KEY, "");
      BaseSwipeFragment fragment;
      if (TextUtils.isEmpty(token) || TextUtils.isEmpty(userInfo)) {
        fragment = new LoginFragment();
      } else {
        loginTIM();
        fragment = new HomeFragment();
        boolean isEquipment =
            (boolean) SPUtils.get(mActivity, SpKeyConstant.IS_EQUIPMENT_KEY, false);
        String equipmentId = (String) SPUtils.get(mActivity, SpKeyConstant.IS_EQUIPMENT_ID_KEY, "");
        if (equipmentId.equals(MyApplication.getInstance().getUserInfo().getUserId())
            && isEquipment) {
          startActivity(new Intent(this, VerPwdInputActivity.class));
        }
      }
      getSupportFragmentManager()
          .beginTransaction()
          .add(getContextViewId(), fragment, fragment.getClass().getSimpleName())
          .addToBackStack(fragment.getClass().getSimpleName())
          .commit();
    }
  }

  @Override public void initView() {

  }

  /*
   *  设置当前用户的用户配置
   *  在初始化之后登录之前设置
   * */
  private void setTIMUserConfig() {
    TIMUserConfig userConfig = new TIMUserConfig()
        //设置用户状态变更事件监听器
        .setUserStatusListener(new TIMUserStatusListener() {
          @Override
          public void onForceOffline() {
            //被其他终端踢下线
            reLogin(1);
          }

          @Override
          public void onUserSigExpired() {
            //登录过期，需要重新登录
            reLogin(2);
          }
        })
        //设置连接状态事件监听器
        .setConnectionListener(new TIMConnListener() {
          @Override
          public void onConnected() {
          }

          @Override
          public void onDisconnected(int code, String desc) {
          }

          @Override
          public void onWifiNeedAuth(String name) {
          }
        })
        //设置群组事件监听器
        .setGroupEventListener(timGroupTipsElem -> {

        })
        //设置会话刷新监听器
        .setRefreshListener(new TIMRefreshListener() {
          @Override public void onRefresh() {

          }

          @Override public void onRefreshConversation(List<TIMConversation> list) {

          }
        });

    RefreshEvent.getInstance().init(userConfig);
    userConfig = FriendshipEvent.getInstance().init(userConfig);
    userConfig = GroupEvent.getInstance().init(userConfig);
    userConfig = MessageEvent.getInstance().init(userConfig);
    TIMManager.getInstance().setUserConfig(userConfig);
  }

  /*
   *  登录腾讯IM
   * */
  private void loginTIM() {
    LoginBusiness.loginIm(MyApplication.getInstance().getThirdAccId(),
        MyApplication.getInstance().getUserInfo().getThirdToken(), this);
    //LoginBusiness.loginIm(Constants.IDENTIFY, Constants.USERSIG, this);
  }

  /*
   *  type 1 被其他终端踢下线 2 登录过期，需要重新登录
   *  登录异常的情况，情况账号信息，重新登录
   * */
  private void reLogin(int type) {
    String toastTip = "登录异常，请重新登录";
    if (type == 1) toastTip = "账号在其他地方登录，请重新登录";
    if (type == 2) toastTip = "登录已过期，请重新登录";
    Toast.makeText(this, toastTip, Toast.LENGTH_SHORT).show();
    SPUtils.put(this, SpKeyConstant.TOKEN_KEY, "");
    SPUtils.put(this, SpKeyConstant.USERINFO_KEY, "");
    AppManagerUtil.getAppManager().finishAllActivity();
    startActivity(new Intent(this, SplashActivity.class));
  }

  /*
   *  登录腾讯IM失败
   * */
  @Override public void onError(int code, String s) {
    // 腾讯IM有处理重连的情况，所以这边无需做重连，可以通过code 做一些对应的处理 （暂时不做处理）
    LoginBusiness.loginIm(MyApplication.getInstance().getThirdAccId(),
        MyApplication.getInstance().getUserInfo().getThirdToken(), this);
  }

  /*
   *  登录腾讯IM成功
   */
  @Override public void onSuccess() {
    //程序后台后消息推送
    PushUtil.getInstance();
    //消息监听
    MessageEvent.getInstance();
    List<TIMAddFriendRequest> timAddFriendRequests = new ArrayList<>();
    UserInfo userInfo = MyApplication.getInstance().getUserInfo();
    if (null != userInfo) {
      timAddFriendRequests.add(
          new TIMAddFriendRequest(userInfo.getQqFeedBackName()));
      timAddFriendRequests.add(
          new TIMAddFriendRequest(userInfo.getQqServiceName()));
      TIMFriendshipManagerExt.getInstance().addFriend(timAddFriendRequests,
          new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override public void onError(int i, String s) {

            }

            @Override public void onSuccess(List<TIMFriendResult> timFriendResults) {

            }
          });
    }
  }

  // ---------  以下三种情况都属于登录成功，都需要去登录 TIM ----------
  /*
   * 注册成功
   * */
  @Subscribe(code = RxBusCode.REG_SUCCESS_CODE)
  public void regSuccess() {
    loginTIM();
  }

  /*
   * 登录成功
   * */
  @Subscribe(code = RxBusCode.LOGIN_SUCCESS_CODE)
  public void loginSuccess() {
    loginTIM();
  }

  /*
   * 快速登录成功
   * */
  @Subscribe(code = RxBusCode.FAST_LOGIN_SUCCESS_CODE)
  public void fastLoginSuccess() {
    loginTIM();
  }

  @Override public void onBackPressed() {

    if (getCurrentFragment() instanceof HomeFragment) {

      if (isTheOneBack) {
        showToast(R.string.press_twice_to_exit);
        isTheOneBack = false;
        new Handler().postDelayed(() -> isTheOneBack = true, 2000);
      } else {
        super.onBackPressed();
      }
    } else {
      super.onBackPressed();
    }
  }

  @Override protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    popBackStack(HomeFragment.class);
    RxBus.get().send(RxBusCode.SYSTEM_PUSH_CODE);
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    FloatWindow.destroy("old");
    FloatWindow.destroy("cancel");
    FloatWindow.destroy("cancel2");
    FloatWindow.cancel();
    RxBus.get().unRegister(this);
  }
}
